import Config from './config.js'
import Util from './util.js'
import store from '../store'
import {toLogin,outLogin} from './login.js'


// #ifdef H5
const app_type = 'h5';
const app_type_name = 'H5';
// #endif

// #ifdef MP-WEIXIN
const app_type = 'weapp';
const app_type_name = '微信小程序';
// #endif

// #ifdef MP-ALIPAY
const app_type = 'aliapp';
const app_type_name = '支付宝小程序';
// #endif

// #ifdef MP-BAIDU
const app_type = 'baiduapp';
const app_type_name = '百度小程序';
// #endif

// #ifdef MP-TOUTIAO
const app_type = 'MP-TOUTIAO';
const app_type_name = '头条小程序';
// #endif

// #ifdef MP-QQ
const app_type = 'MP-QQ';
const app_type_name = 'QQ小程序';
// #endif

// #ifdef APP-PLUS
const app_type = 'app';
const app_type_name = 'APP';
// #endif

function error(code,msg,requestData){
	if (code === 408 || code === 401) {// 需要重新登录
		// store.commit('setToken',null);
		// store.commit('setUserIdData',null);
		outLogin();
		toLogin();
	}else if(code === 404){
		Util.requestToast({title: "404，路径找不到"})
	}else if(code === 503){
		Util.requestToast({title: "服务不可用"})
	}else if(code === 504){
		Util.requestToast({title: "网络连接错误"})
	}else{
		Util.requestToast({title: msg})
	}
}

function sendRequest(params) {
	var method = params.method?params.method : 'GET', // 请求方式
		url = params.url, // 请求路径
		data = {},
		header = params.header || {}
	header['Content-Type'] = 'application/json; charset=UTF-8;application/json;Access-Control-Allow-Origin:*';
	let token = uni.getStorageSync('token');
	if(!header.Authorization) header.Authorization = params.noToken?'':(token?'Bearer '+token:'');
	if (params.data != undefined) Object.assign(data, params.data);
	if(!params.hideLoad) uni.showLoading();
	let requestData = params;
	requestData.method = method;
	requestData.url = url;
	requestData.header = header;
	requestData.data = data;
	requestData.dataType = params.dataType || 'json';
	requestData.responseType = params.responseType || 'text';
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: Config.baseUrl + requestData.url,
			method: requestData.method,
			data: requestData.data,
			header: requestData.header,
			dataType: requestData.dataType,
			responseType: requestData.responseType,
			success: (res) => {
				if(res.data.code === 401){
					let requestList = store.state.requestList;
					const refreshTokenStatus = store.state.refreshTokenStatus;
					const refreshState = store.state.refreshState;
					if (!refreshTokenStatus) {
					  store.state.refreshTokenStatus = true;
					  requestData.hideLoad = true;
					  let fun = function() {
					  	resolve(sendRequest(requestData));
					  }
					  requestList.push(fun);
					  store.state.requestList = requestList;
					  if (store.state.userIdData && store.state.userIdData.refreshToken) {
					    refreshTokenFun().then(refreshTokenRes=>{
							let accessToken = refreshTokenRes.data.accessToken;
							store.commit('setToken',accessToken);
							store.commit('setRefreshState',true);

							let cbFun = function() {
								let requestListItem = requestList.shift();
								store.state.requestList = requestList;
								if (requestListItem) {
									requestListItem();
									if(requestList && requestList.length>0){
										cbFun();
									}
								}
							}
							cbFun();
					    })
					    .catch(refreshTokenRes=>{
							// store.commit('setToken',null);
							// store.commit('setUserIdData',null);
							outLogin();
							toLogin();
						})
					  }else{
						  // store.commit('setToken',null);
						  // store.commit('setUserIdData',null);
						  outLogin();
						  toLogin();
					  }
					}
					else {
						if(!refreshState){
							requestData.hideLoad = true;
							let fun = function() {
								resolve(sendRequest(requestData));
							}
							requestList.push(fun);
							store.state.requestList = requestList;
						}else{
							if(res && res.statusCode !== 200) {
								error(res.statusCode,res.errMsg);
								reject(res)
							}else if(res.data && res.data.code !== 0){
								error(res.data.code,res.data.msg);
								reject(res)
							}
							resolve(res.data);
						}
					}
				}else{
					if(res && res.statusCode !== 200) {
						error(res.statusCode,res.errMsg);
						reject(res)
					}else if(res.data && res.data.code !== 0){
						error(res.data.code,res.data.msg);
						reject(res)
					}
					resolve(res.data);
				}
			},
			fail: (res) => {
				error(res.statusCode,res.errMsg);
				reject(res);
			},
			complete: (res) => {
				uni.hideLoading();
			}
		});
	});
}

// 单文件上传
export function upload(url, filePath,filename, formData,header,success,fail){
	let name = filename || 'file';
	header = header || {};
	header["Content-Type"] = "multipart/form-data;"
	let token = uni.getStorageSync('token');
	if(!header.Authorization) header.Authorization = header.noToken?'':(token?'Bearer '+token:'');
	let requestData = {};
	requestData.url = url;
	requestData.filePath = filePath;
	requestData.formData = formData;
	requestData.header = header;
	
	let promise = new Promise((resolve,reject)=>{
		uni.uploadFile({
			url: Config.baseUrl + requestData.url,
			filePath: requestData.filePath,
			name: 'file',
			formData: requestData.formData || {},
			header: requestData.header,
			success: res => {
				let data = res.data?JSON.parse(res.data):null;
				
				if(data.code === 401){
					let requestList = store.state.requestList;
					const refreshTokenStatus = store.state.refreshTokenStatus;
					const refreshState = store.state.refreshState;
					if (!refreshTokenStatus) {
					  store.state.refreshTokenStatus = true;
					  requestData.hideLoad = true;
					  let fun = function() {
					  	resolve(sendRequest(requestData));
					  }
					  requestList.push(fun);
					  store.state.requestList = requestList;
					  if (store.state.userIdData && store.state.userIdData.refreshToken) {
					    refreshTokenFun().then(refreshTokenRes=>{
							let accessToken = refreshTokenRes.data.accessToken;
							store.commit('setToken',accessToken);
							store.commit('setRefreshState',true);
				
							let cbFun = function() {
								let requestListItem = requestList.shift();
								store.state.requestList = requestList;
								if (requestListItem) {
									requestListItem();
									if(requestList && requestList.length>0){
										cbFun();
									}
								}
							}
							cbFun();
					    })
					    .catch(refreshTokenRes=>{
							// store.commit('setToken',null);
							// store.commit('setUserIdData',null);
							outLogin();
							toLogin();
						})
					  }else{
						  // store.commit('setToken',null);
						  // store.commit('setUserIdData',null);
						  outLogin();
						  toLogin();
					  }
					}
					else {
						requestData.hideLoad = true;
						let fun = function() {
							resolve(sendRequest(requestData));
						}
						requestList.push(fun);
						store.state.requestList = requestList;
					}
				}else{
					if(res && res.statusCode !== 200) {
						error(res.statusCode,res.errMsg);
						reject(res)
					}else if(res.data && data.code !== 0){
						error(data.code,data.msg);
						reject(res)
					}
					resolve(data);
				}
			},
			fail: (res) => {
				error(res.statusCode,res.errMsg);
				reject(res);
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	})
	return promise;
}


// 刷新token
function refreshTokenFun(cb){
	let header = {};
	header['Content-Type'] = 'application/json; charset=UTF-8;application/json;Access-Control-Allow-Origin:*';
	header.Authorization = '';  //token设置为空
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${Config.baseUrl}/system/auth/refresh-token?refreshToken=${store.state.userIdData.refreshToken}`,
			method: 'POST',
			header: header,
			dataType: 'json',
			responseType: 'text',
			success: (res) => {
				if(res && res.statusCode !== 200) {
					reject(res)
				}else if(res.data && res.data.code !== 0){
					reject(res)
				}
				resolve(res.data);
			},
			fail: (res) => {
				reject(res);
			},
			complete: (res) => {
				uni.hideLoading();
			}
		});
	});
}



export default {sendRequest};